package com.wsc.springbootmultidevdemo.controller;

import com.sun.deploy.net.HttpRequest;
import com.wsc.springbootmultidevdemo.pojo.User;
import com.wsc.springbootmultidevdemo.service.AsyncTask;
import com.wsc.springbootmultidevdemo.service.impl.AsyncTask1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 异步任务处理
 */
@RestController
@RequestMapping("/api/cc")
@EnableAsync
public class AsyncTaskCtrl {

    @Autowired
    AsyncTask asyncTask;

    /**
     * 同步任务
     */
    @GetMapping("/synctest")
    public String syncTask(){
        asyncTask.syncTask();
        System.out.println(Thread.currentThread().getName()+"==========主线程名称");
        return "同步任务,执行完成";
    }

    /**
     * 异步任务1:线程池，创建新线程处理
     * @return
     */
    @GetMapping("/async1")
    public String asyncTask1(){
        //新建一个线程池
        ExecutorService service = Executors.newFixedThreadPool(5);
        AsyncTask1 asyncTask1 = new AsyncTask1();
        //线程池分出一条线程执行读取任务
        service.execute(asyncTask1);
        System.out.println(Thread.currentThread().getName()+"==========当前线程名称");
        return "异步任务,执行完成";
    }

    /**
     * 使用注解的方式来执行异步任务
     * @return
     */
    @GetMapping("/async2")
    public String asyncTask2(){
        asyncTask.asyncTask1();
        System.out.println(Thread.currentThread().getName()+"==========当前线程名称");
        return "异步任务,执行完成";
    }

    /**
     * requestBody 测试
     * @return
     */
    @PostMapping("/adduser")
    public void showUser(@RequestBody User user){
        System.out.println(user);
    }

    /**
     * requestPara 测试
     */
    @PostMapping("/adduser1")
    public void  showUser1(@RequestParam String name, @RequestParam String age, @RequestParam String sex, HttpServletRequest req){
        User user = new User();
        System.out.println(req.getParameter("sex"));
        user.setName(name);
        user.setAge(Integer.parseInt(age));
        user.setSex(sex);
        System.out.println(user);
    }

}
